Download streamflow data from USGS (from assignment 21)
# Example: Cache la Poudre River at Mouth (USGS site 06752260)poudre_flow <-readNWISdv(siteNumber ="06752260", # Download data from USGS for site 06752260parameterCd ="00060", # Parameter code 00060 = discharge in cfs)startDate ="2013-01-01", # Set the start dateendDate ="2023-12-31") |># Set the end daterenameNWISColumns() |># Rename columns to standard names (e.g., "Flow", "Date")mutate(Date =as_date(Date),Date =floor_date(Date, "month")) |># Convert daily Date values into a year-month format (e.g., "2023 Jan")group_by(Date) |># Group the data by the new monthly Datesummarise(Flow =mean(Flow),.groups ="drop") # Calculate the average daily flow for each month
# Plotting the time serieslibrary(ggplot2)library(plotly)
Warning: package 'plotly' was built under R version 4.4.3
Attaching package: 'plotly'
The following object is masked from 'package:ggplot2':
last_plot
The following object is masked from 'package:stats':
filter
The following object is masked from 'package:graphics':
layout
flowplot <-ggplot(poudre_ts, aes(x = Date, y = Flow)) +geom_line() +labs(title ="Monthly Mean Discharge\nCache la Poudre River (2013–2023)",x ="Year‑Month", y ="Discharge (cfs)")print(flowplot)
compare_tbl <- forecast_tbl %>%left_join(obs_2024, by ="Date")r2_val <-summary(lm(Observed ~ Predicted, data = compare_tbl))$r.squaredcat("R² = ", round(r2_val, 3)," → ", round(r2_val *100, 1),"% of observed monthly variance explained by the forecasts.\n", sep ="")
R² = 0.919 → 91.9% of observed monthly variance explained by the forecasts.
# The R-squared value tells us what proportion of variance between variables can be explained by the forecasts. This model has a R-squared value of around 92% which shows us that there is strong explanatory power as it explains 92% of month-to-month variability in the observed 2024 flows very accurately.
Predicted vs Observed Values
ggplot(compare_tbl, aes(x = Predicted, y = Observed, color =factor(.model_id))) +geom_point(color="darkblue", size =2) +geom_abline(slope =1, intercept =0, linetype ="dashed") +# 1:1 linegeom_smooth(color="pink",method ="lm", se =FALSE) +# fit linelabs(title =" 2024 Forecasted vs Observed Monthly Flow",subtitle =paste0("Models (IDs) & R² = ", round(r2_val, 3)),x ="Forecasted Mean (cfs)",y ="Observed Mean (cfs)",color ="Model\nID" ) +theme_minimal()